﻿/*
  Copyright (c) 2009, Onder Ezdi
  All rights reserved.

  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
  
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the 
    documentation and/or other materials provided with the distribution.
  
  * Neither the name of Onder Ezdi nor the names of its 
    contributors may be used to endorse or promote products derived from 
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * FileCopier
 * Creates a file copy or move class to handle with progress and other various events.
 * 
 * @author		Onder Ezdi
 * @version		1.00.03
 *
 */

package makeeasier.air.file {
	
	import flash.filesystem.*;
	import flash.utils.Timer;
	import flash.utils.ByteArray;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	
	
	public class FileCopier extends EventDispatcher {
		
		public static var INIT:String = "init";
		public static var PROGRESS:String = "progress";
		public static var COMPLETE:String = "complete";
		public static var STARTED:String = "started";
		public static var STOPPED:String = "stopped";
		public static var FILE_MOVE_ERROR:String = "fileMoveError";
		public static var FILE_READ_ERROR:String = "fileReadError";
		public static var FILE_WRITE_ERROR:String = "fileWriteError";
		public static var FILE_OPEN_ERROR:String = "fileOpenError";
		public static var SOURCE_OPEN_ERROR:String = "sourceOpenError";
		public static var SOURCE_READ_ERROR:String = "sourceReadError";
		public static var SOURCE_WRITE_ERROR:String = "sourceWriteError";
		public static var SOURCE_DELETE_ERROR:String = "sourceDeleteError";
		public static var DESTINATION_READ_ERROR:String = "destinationReadError";
		public static var DESTINATION_WRITE_ERROR:String = "destinationWriteError";
		public static var OVERWRITE:String = "overwrite";
		
		private var _source:File;								//source file
		private var _destination:File;							//destination file
		private var stackTimer:Timer;							//stack reader timer, can be useful when need some performance tweak
		private var ba:ByteArray;								//byteArray for reading stacks
		private var _sourceStream:FileStream;					//source file reader stream
		private var _destinationStream:FileStream;				//destination file writer stream
		private var stackStart:Number = 0;						//stack start position
		private var _stackSize:Number = 8192 * 128; 			//stack size per read operation (in bytes) Default = 1mb (1048576 byte)
		private var _bytesLoaded:Number;						//loaded bytes of copied or moved file
		private var _bytesTotal:Number;							//total bytes of copied or moved file
		private var _readDensity:Number;						//reading density, mean timer frequency, can be useful when need some performance tweak
		private var _workingMode:String;						//working mode for class, "copy" or "move", default is "copy" mode.
		private var _state:String;								//state of class, "init", "working", "stopped" etc...
		private var _overWrite:Boolean							//overwrite destination
		
		/**
		 * Constructor 
		 */
		public function FileCopier(wm:String = "copy"){
			stackStart = 0;
			_stackSize = 8192 * 128; // in bytes
			
			_workingMode = wm;
			_overWrite = false;
			_readDensity = 10;
			
			stackTimer = new Timer(_readDensity);
			stackTimer.addEventListener(TimerEvent.TIMER, doWork);
			
			ba = new ByteArray();
			
			_state = "init";
			
			dispatchEvent(new Event(INIT));
		}
		
		/**
		 * start
		 * starts copy or move process
		 */
		public function start():void{
			if(!_source || !_destination){
				throw new Error("Class initialize error. Please set source or destination files first.");
			}
			_state = "working";
			
			//Overwrite Check
			if(_destination.exists){
				//throw new Error("File found at given destination with same filename.");
				if(_overWrite){
					if(_destination.isDirectory){
						_destination.deleteDirectory(true);
					} else {
						_destination.deleteFile();
					}
				} else {
					dispatchEvent(new Event(OVERWRITE));
					dispatchEvent(new Event(COMPLETE));
					return;
				}
			}
			stackTimer.addEventListener(TimerEvent.TIMER, doWork);
			stackTimer.start();
			dispatchEvent(new Event(STARTED));
		}
		
		/**
		 * stop
		 * stop copy or move process
		 */
		public function stop():void{
			_state = "stopped";
			stackTimer.removeEventListener(TimerEvent.TIMER, doWork);
			stackTimer.stop();
			dispatchEvent(new Event(STOPPED));
		}
		
		
		/**
		 * togglePause
		 * toggling pause mode for copy or move process
		 */
		/* //this can be activated to make different uses of class.
		public function togglePause():void{
			if(_state != "paused"){
				_state = "paused";
				stackTimer.removeEventListener(TimerEvent.TIMER, doWork);
				stackTimer.stop();
			} else {
				_state = "working";
				stackTimer.addEventListener(TimerEvent.TIMER, doWork);
				stackTimer.start();
			}
		}
		*/
		
		/**
		 * doWork
		 * copying or moving files
		 */
		private function doWork(e:Event):void{
			stackTimer.stop();
			
			ba = new ByteArray();
			
			try{
				_sourceStream.open(_source,FileMode.READ);
			} catch(e:Error) {
				//throw new Error("Cannot read from source file");
				dispatchEvent(new Event(SOURCE_OPEN_ERROR));
			}
			
			try{
				_destinationStream.open(_destination,FileMode.APPEND);
			} catch(e:Error) {
				//throw new Error("Cannot read from source file");
				dispatchEvent(new Event(DESTINATION_WRITE_ERROR));
			}
			
			try{
				_sourceStream.position = stackStart;
			} catch(e:Error){
				//asd
			}
			
			if(_sourceStream.bytesAvailable > _stackSize){
				
				try {
					_sourceStream.readBytes(ba, stackStart, _stackSize);
				} catch(e:Error) {
					//throw new Error("Cannot read from source file");
					dispatchEvent(new Event(SOURCE_READ_ERROR));
				}
				
				try {
					_destinationStream.writeBytes(ba, stackStart, _stackSize);
				} catch(e:Error) {
					//throw new Error("Cannot write to destination file");
					dispatchEvent(new Event(DESTINATION_WRITE_ERROR));
				}
				
			} else {
				try {
					_sourceStream.readBytes(ba, stackStart, _sourceStream.bytesAvailable);
				} catch(e:Error) {
					//throw new Error("Cannot read from source file");
					dispatchEvent(new Event(SOURCE_READ_ERROR));
				}
				try {
					_destinationStream.writeBytes(ba, stackStart, _sourceStream.bytesAvailable);
				} catch(e:Error) {
					//throw new Error("Cannot write to destination file");
					dispatchEvent(new Event(DESTINATION_WRITE_ERROR));
				}
				if(_workingMode == "move"){
					try {
						_source.deleteFile();
					} catch(e:Error){
						//throw new Error("Cannot delete source file during move. Probably file in use or file already moved or deleted.");
						dispatchEvent(new Event(SOURCE_DELETE_ERROR));
					}
				}
				
				dispatchEvent(new Event(COMPLETE));
				
				_sourceStream.close();
				_destinationStream.close();
			
				return;
			}
			
			
			_bytesLoaded = stackStart;
			
			dispatchEvent(new Event(PROGRESS));
			stackStart += _stackSize;
			
			_sourceStream.close();
			_destinationStream.close();
			
			stackTimer.start();
		}
		
		/**
		 * source
		 * get source
		 */
		public function get source():String{
			return _source.nativePath;
		}
		
		/**
		 * source
		 * set source
		 */
		public function set source(s:String):void{
			_source = new File(s);
			_sourceStream = new FileStream();
		}
		
		/**
		 * destination
		 * get destination
		 */
		public function get destination():String{
			return _destination.nativePath;
		}
		
		/**
		 * destination
		 * set destination
		 */
		public function set destination(s:String):void{
			_destination = new File(s);
			_destinationStream = new FileStream();
		}
		
		/**
		 * stackSize
		 * get stack size
		 */
		public function get stackSize():Number{
			return _stackSize;
		}
		
		/**
		 * stackSize
		 * set stack size
		 */
		public function set stackSize(n:Number):void{
			_stackSize = n;
		}
		
		/**
		 * readDensity
		 * get read density
		 */
		public function get readDensity():Number{
			return _readDensity;
		}
		
		/**
		 * readDensity
		 * set read density
		 */
		public function set readDensity(n:Number):void{
			var isWorking = stackTimer.running;
			if(isWorking){
				stackTimer.removeEventListener(TimerEvent.TIMER, doWork);
				stackTimer.stop();
			}
			_readDensity = n;
			stackTimer = new Timer(n);
			if(isWorking){
				stackTimer.addEventListener(TimerEvent.TIMER, doWork);
				stackTimer.start();
			}
		}
		
		/**
		 * state
		 * get class working state
		 */
		public function state():String{
			return _state;
		}
		
		/**
		 * state
		 * get loaded bytes of source file
		 */
		public function get bytesLoaded():Number{
			return _bytesLoaded;
		}
		
		/**
		 * bytesTotal
		 * get total bytes of source file
		 */
		public function get bytesTotal():Number{
			return _source.size;
		}
		
		
		
	}
	
	
}
